package com.jimmy.dreamer;

import android.app.Activity;
import android.os.Bundle;

import static android.provider.BaseColumns._ID;
import static com.jimmy.dreamer.DbConstants.USRNAME;
import static com.jimmy.dreamer.DbConstants.PWD;
import static com.jimmy.dreamer.DbConstants.TABLE_NAME;
import static com.jimmy.dreamer.Dreamer.isLogin;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Login extends Activity implements OnClickListener{
	private DbHelper dbhelper = null;

    private EditText username = null;
    private EditText password = null;
    private Button btnLogin = null;
    private Button btnReg = null;

    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        initView();

        openDatabase();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDatabase();
    }
    private void openDatabase(){
        dbhelper = new DbHelper(this); 
    }

    private void closeDatabase(){
        dbhelper.close();
    }

    private void initView(){
    	username = (EditText) findViewById(R.id.txt_usname);
        password = (EditText) findViewById(R.id.txt_pwd);
        btnLogin = (Button) findViewById(R.id.btn_login1);
        btnLogin.setOnClickListener(this);
        btnReg = (Button) findViewById(R.id.btn_reg);
        btnReg.setOnClickListener(this);
        
    }
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_login1:
            if(logincheck()){
            	isLogin = true;
            	Intent d = new Intent(this, Dreamer.class);
        		startActivity(d);
            }
            else{
            	isLogin = false;
            	Intent d = new Intent(this, Dreamer.class);
        		startActivity(d);
            }
            break;
            
        case R.id.btn_reg:
        	Intent r = new Intent(this, Register.class);
    		startActivity(r);
            break;

        default:
        }
    }
    private boolean logincheck(){

        Cursor cursor = getCursor();
        
        while(cursor.moveToNext()){
        	if(cursor.getString(1).equals(username.getText().toString()) && cursor.getString(2).equals(password.getText().toString()))return true;
        }
        return false;
    }
    private Cursor getCursor(){
        SQLiteDatabase db = dbhelper.getReadableDatabase();
        String[] columns = {_ID, USRNAME, PWD};

        Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
        startManagingCursor(cursor);

        return cursor;
    }
}